package com.sky.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.codehaus.jettison.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 调用百度地图的接口工具
 */

public class BaiduMapUtil {

    /**
     * 调用百度接口获取地址经纬度
     * @param address
     * @param ak
     * @return
     * @throws Exception
     */
    public static Map<String, String> getLngAndLat(String address, String ak) throws Exception {
        final String longitudeLatitude = "https://api.map.baidu.com/geocoding/v3/";
        String url = longitudeLatitude + "?address=" + address + "&output=json" + "&ak=" + ak;
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String s = EntityUtils.toString(entity);
        JSONObject jsonObject = new JSONObject(s);
        String lng = jsonObject.getJSONObject("result").getJSONObject("location").getString("lng");
        String lat = jsonObject.getJSONObject("result").getJSONObject("location").getString("lat");
        String resultlng = lng.substring(0, lng.indexOf(".")) + "." + lng.substring(lng.indexOf(".") + 1, lng.indexOf(".") + 7);
        String resultlat = lat.substring(0, lat.indexOf(".")) + "." + lat.substring(lat.indexOf(".") + 1, lat.indexOf(".") + 7);
        Map<String, String> map = new HashMap<>();
        map.put("lng", resultlng);
        map.put("lat", resultlat);
        response.close();
        httpClient.close();
        return map;
    }

    /**
     * 调用百度接口获取两个地址之间的路线信息(返回值为字符串需要转json)
     * @param origin
     * @param destination
     * @param ak
     * @return
     * @throws Exception
     */
    public static String getRouteMassenge(Map<String, String> origin, Map<String, String> destination, String ak) throws Exception {
        //GET请求 /driving?origin=40.01116,116.339303&destination=39.936404,116.452562&ak=您的AK
        final String information = "https://api.map.baidu.com/directionlite/v1/riding";
        String sorigin = origin.get("lat") + "," + origin.get("lng");
        String sdestination = destination.get("lat") + "," + destination.get("lng");
        String url = information + "?origin=" + sorigin + "&destination=" + sdestination + "&ak=" + ak;
        System.out.println(url);
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String s = EntityUtils.toString(entity);
        response.close();
        httpClient.close();
        return s;
    }
}
